package br.com.afi.util.hibernate.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Classe que verifica a String ou o Number é um CPF válido.
 * 
 * @author André de Fontana Ignacio
 * @version 1.0
 */
public class CPFValidator implements ConstraintValidator<CPF, Object>
{
	@Override
	public void initialize( CPF parameters ){
		
	}

	@Override
	public boolean isValid( Object value, ConstraintValidatorContext constraintContext )
	{
		String cpf = null;
		if ( value == null )
		{
			return true;
		}
		if ( value instanceof Number )
		{
			cpf = value.toString();
		}
		else if ( ( value instanceof String ) )
		{
			cpf = ( String ) value;
		}
		else
		{
			return false;
		}

		if ( cpf.isEmpty() )
		{
			return true;
		}

		if ( cpf.length() != 11 || "11111111111".equals( cpf ) )
		{
			return false;
		}

		int dig[] = new int[11];
		int digV[] = new int[2];
		int restoAux;

		for ( int i = 0; i < 11; i++ )
		{
			dig[i] = Integer.parseInt( cpf.substring( i, i + 1 ) );
		}
		final int somaprod1 = dig[0] * 10 + dig[1] * 9 + dig[2] * 8 + dig[3] * 7 + dig[4] * 6 + dig[5] * 5 + dig[6] * 4 + dig[7] * 3 + dig[8] * 2;
		restoAux = somaprod1 % 11;

		digV[0] = ( restoAux < 2 ? 0 : 11 - restoAux );

		final int somaprod2 = dig[0] * 11 + dig[1] * 10 + dig[2] * 9 + dig[3] * 8 + dig[4] * 7 + dig[5] * 6 + dig[6] * 5 + dig[7] * 4 + dig[8] * 3 + digV[0] * 2;
		restoAux = somaprod2 % 11;

		digV[1] = restoAux < 2 ? 0 : 11 - restoAux;

		return digV[0] == dig[9] && digV[1] == dig[10];
	}

}
